<template>
  <div class="home">
    <div class="navbar">
      <el-input
        placeholder="搜索商店..."
        v-model="searchQuery"
        class="search-input"
        @keyup.enter="performSearch"
      ></el-input>
      <el-button type="primary" @click="performSearch">搜索</el-button>
    </div>

    <div class="main-section">
      <h2>商店列表</h2>
      <div class="main-content">
        <el-card v-for="shop in filteredShops" :key="shop.id" class="item-card">
          <div class="item-info">
            <h3>{{ shop.shop_name }}</h3>
            <p>{{ shop.shop_description }}</p>
            <p>价格：{{ shop.shop_price }}</p>

            <img :src="shop.shop_img" alt="商店图片" class="shop-image" />
            <div class="button">
              <el-button type="success" @click="addToCart(shop.id)"
                >加入购物车</el-button
              >

              <el-button type="info" @click="viewRatings(shop.id)"
                >查看详情</el-button
              >
            </div>
            <!-- 新增查看详情按钮 -->
          </div>
        </el-card>
      </div>
    </div>
    <div class="sales-ranking">
      <h2>热销商品排行榜</h2>
      <el-card
        v-for="(product, index) in topProducts"
        :key="product.id"
        class="ranking-card"
      >
        <div class="ranking-info">
          <h3>{{ index + 1 }}. {{ product.shop_name }}</h3>
          <!-- 显示自增的数字 -->
          <img :src="product.shop_img" alt="商品图片" class="ranking-image" />
        </div>
        <div style="margin-left: 715px">
          <el-button type="success" @click="addToCart(product.id)"
            >加入购物车</el-button
          >
          <el-button type="info" @click="viewRatings(product.id)"
            >查看详情</el-button
          >
        </div>
      </el-card>
    </div>
    <!-- 支付弹窗 -->
    <el-dialog title="支付确认" :visible.sync="paymentDialogVisible">
      <p>您选择的商品: {{ selectedShop.shop_name }}</p>
      <p>商品总计: {{ selectedShop.shop_price }} 元</p>
      <p>请确认支付信息。</p>
      <span>支付方式: <strong>第三方支付</strong></span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment">确认支付</el-button>
      </div>
    </el-dialog>

    <!-- 评价弹窗 -->
    <el-dialog
      title="商品评价"
      :visible.sync="ratingsDialogVisible"
      width="600px"
    >
      <div v-if="ratings.length > 0">
        <el-list>
          <el-list-item
            v-for="rating in ratings"
            :key="rating.id"
            class="rating-item"
          >
            <div class="rating-header">
              <strong>用户名：{{ rating.username }}</strong>
              <span class="rating-score">评分: {{ rating.rating }}</span>
            </div>
            <p class="rating-comment">{{ rating.comment }}</p>
          </el-list-item>
        </el-list>
      </div>
      <div v-else>
        <p>暂无评价。</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ratingsDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios"; // 导入 Axios

export default {
  data() {
    return {
      searchQuery: "",
      shops: [], // 初始化商店数组
      topProducts: [], // 新增销量排行榜数据
      userId: null, // 用于存储用户 ID
      paymentDialogVisible: false, // 控制支付弹窗的显示
      selectedShop: {}, // 用于存储选中的商店信息
      ratingsDialogVisible: false, // 控制评价弹窗的显示
      ratings: [], // 用于存储商品评价
    };
  },
  computed: {
    filteredShops() {
      if (!this.searchQuery) return this.shops; // 如果没有搜索内容，返回所有商店
      return this.shops.filter(
        (shop) =>
          shop.shop_name.includes(this.searchQuery) || // 根据商店名称过滤
          shop.shop_description.includes(this.searchQuery) // 根据商店描述过滤
      );
    },
  },
  methods: {
    performSearch() {
      console.log("搜索:", this.searchQuery); // 打印搜索内容
    },
    fetchShops() {
      // 发送请求获取商店数据
      axios
        .get("/GetProductsList") // 替换为你的 API 地址
        .then((response) => {
          console.log("首页获取到的数据:", response.data); // 打印获取到的数据
          if (response.data.code === 200) {
            this.shops = response.data.data.map((shop) => {
              return {
                ...shop,
                shop_img: `data:image/jpeg;base64,${shop.shop_img}`, // 将 Base64 编码转换为可用的 URL
              };
            });
          } else {
            console.error("获取商店数据失败:", response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取商店数据失败:", error);
        });
    },
    addToCart(shopId) {
      const userId = localStorage.getItem("userId"); // 从 localStorage 获取用户 ID
      if (!userId) {
        this.$message.error("请先登录！"); // 如果用户未登录，提示错误
        this.$router.push("/login"); // 跳转到登录页面
        return;
      }
      axios
        .post("/AddIntoCart", {
          user_id: userId,
          product_id: shopId,
        })
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("添加成功！"); // 使用 Element UI 的消息提示
          } else {
            this.$message.error("添加失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("添加购物车失败:", error);
          this.$message.error("添加失败，请重试。");
        });
    },
    fetchTopProducts() {
      // 发送请求获取销量排行榜数据
      axios
        .get("/SelTop") // 替换为你的 API 地址
        .then((response) => {
          console.log("销量排行榜数据:", response.data); // 打印获取到的数据
          if (response.data.code === 200) {
            this.topProducts = response.data.data.map((product) => {
              return {
                ...product,
                shop_img: `data:image/jpeg;base64,${product.shop_img}`, // 将 Base64 编码转换为可用的 URL
              };
            });
          } else {
            console.error("获取销量排行榜数据失败:", response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取销量排行榜数据失败:", error);
        });
    },
    openPaymentDialog(shop) {
      this.selectedShop = shop; // 设置选中的商店信息
      this.paymentDialogVisible = true; // 显示支付弹窗
    },
    confirmPayment() {
      const userId = localStorage.getItem("userId"); // 从 localStorage 获取用户 ID
      if (!userId) {
        this.$message.error("请先登录！"); // 如果用户未登录，提示错误
        this.paymentDialogVisible = false; // 关闭支付弹窗
        return;
      }

      // 准备要发送的数据
      const orderData = {
        customer_id: userId,
        total_price: this.selectedShop.shop_price,
        status: "待发货",
        order_items: [
          {
            product_id: this.selectedShop.id,
            quantity: 1, // 假设每次购买数量为1
            price: this.selectedShop.shop_price,
          },
        ],
      };

      // 发送 POST 请求到后端
      axios
        .post("/orders", orderData)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("订单创建成功！");
            this.paymentDialogVisible = false; // 关闭支付弹窗
          } else {
            this.$message.error("订单创建失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("创建订单失败:", error);
          this.$message.error("创建订单失败，请重试。");
        });
    },
    viewRatings(productId) {
      // 发送请求获取商品评价
      axios
        .get(`/GetRattingById?product_id=${productId}`)
        .then((response) => {
          if (response.data.code === 200) {
            this.ratings = response.data.data; // 设置评价数据
            this.ratingsDialogVisible = true; // 显示评价弹窗
          } else {
            this.$message.error("获取评价失败: " + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("获取评价失败:", error);
          this.$message.error("获取评价失败，请重试。");
        });
    },
  },
  mounted() {
    this.userId = localStorage.getItem("userId"); // 组件挂载时获取用户 ID
    this.fetchShops(); // 组件挂载时获取商店数据
    this.fetchTopProducts(); // 组件挂载时获取销量排行榜数据
  },
};
</script>

<style scoped>
.home {
  padding: 20px;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.main-section {
  margin-top: 20px;
}

.main-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.item-card {
  width: 200px;
  padding: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.item-info {
  text-align: center;
}

.shop-image {
  width: 100%;
  height: 170px;
  margin-bottom: 10px;
}

.button-group {
  /* 新增的样式 */
  display: flex;
  justify-content: space-between; /* 按钮之间的间距 */
  margin-top: 10px; /* 按钮与商品信息之间的间距 */
}

.rating-item {
  border-bottom: 1px solid #e4e7ed;
  padding: 10px 0;
}

.rating-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rating-score {
  color: #f56c6c; /* 红色评分 */
  font-weight: bold;
}

.rating-comment {
  margin-top: 5px;
  color: #606266; /* 评论文字颜色 */
  font-size: 14px;
}

/* 其他样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.sales-ranking {
  margin-top: 20px;
}

.ranking-card {
  margin-bottom: 10px;
}

.ranking-info {
  text-align: center;
}

.item-info .button {
  margin-top: 2px;
}
</style>
